from django.shortcuts import render_to_response
from django.contrib.auth.models import User

from signup.models import SignUpForm, ErrorList

from django.http import HttpResponsePermanentRedirect
from django.core.urlresolvers import reverse

def user_signup(request):
    """
    Show user registration form and validate input.
    """
    
    if request.user.is_authenticated():
        return HttpResponsePermanentRedirect(reverse('url-home'))
    else:
        if request.method == 'POST':
            form = SignUpForm(request.POST, error_class=ErrorList)
            
            if form.is_valid():
                username = form.cleaned_data['username']
                email = form.cleaned_data['email']
                password = form.cleaned_data['password']
                
                user = User.objects.create_user(username, email, password)
                user.save()
                
                return HttpResponsePermanentRedirect(reverse('url-login'))
        else:
            form = SignUpForm()
        
        return render_to_response('signup/base_signup.html', { 'form': form, })
